//
//  AppDelegate.m
//  Recycling
//
//  Created by jzd on 2018/5/16.
//  Copyright © 2018年 宋佳. All rights reserved.
//

#import "AppDelegate.h"
#import "SJRootChoose.h"
#import "NewFeatureController.h"
#import <CoreLocation/CoreLocation.h>
#import <Toast.h>
#import <AFNetworking.h>

@interface AppDelegate ()<CLLocationManagerDelegate>
@property(strong,nonatomic)CLLocationManager *locationManager;
@property (strong,nonatomic)AFNetworkReachabilityManager *networkJudge;
@property (strong,nonatomic) dispatch_source_t timer;
@property (assign,nonatomic) int timeout;

@end

@implementation AppDelegate

-(CLLocationManager *)locationManager{
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        _locationManager.pausesLocationUpdatesAutomatically = NO;
        if (@available(iOS 9.0, *)) {
            _locationManager.allowsBackgroundLocationUpdates = YES;
        } else {
            // Fallback on earlier versions
        }
        _locationManager.distanceFilter = kCLHeadingFilterNone;
        [_locationManager requestAlwaysAuthorization];
    }
    return _locationManager;
}
-(AFNetworkReachabilityManager *)networkJudge{
    if (_networkJudge == nil) {
        _networkJudge = [AFNetworkReachabilityManager sharedManager];
    }
    return _networkJudge;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    
    [UIApplication sharedApplication].statusBarHidden = NO;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    
    [UMConfigure initWithAppkey:@"5b231a49f29d982ed400011a" channel:@"App Store"];
    
    //友盟推送 普通推送详细集成
    // Push组件基本功能配置
    UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
    entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionSound|UMessageAuthorizationOptionAlert;
    
    if (@available(iOS 10.0, *)) {
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    } else {
        // Fallback on earlier versions
    }
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            SJLog(@"granted=YES");
        }else{
            SJLog(@"granted=NO");
        }
    }];
    
    
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    UIViewController *root = [SJRootChoose ChooseRootViewController];
//    NewFeatureController *test = [[NewFeatureController alloc]init];
    self.window.rootViewController = root;
    [self.window makeKeyAndVisible];
    
    
    
    //注册ID
     [WXApi registerApp:@"wx103bedbb07d2e432"];
    
    //开启网络监听
    [self.networkJudge startMonitoring];
    //设置监听
    __block __weak AppDelegate *Copy_self = self;
    [self.networkJudge setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
     {
         if (self.networkJudge.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable)
         {
             [Copy_self.window showToast:@"网络不可用" completion:nil];
         }
         else if (self.networkJudge.networkReachabilityStatus != AFNetworkReachabilityStatusNotReachable)
         {
             SJLog(@"网络正常");
         }
     }];
    
    [self.locationManager startUpdatingLocation];
    
    
    self.timeout = 1;
    NSTimeInterval period = 1.0; //设置时间间隔
    __block __weak AppDelegate *copy_self = self;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue );
    dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, period * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(self.timer, ^{
        
        copy_self.timeout --;
        //2.对timeout进行判断时间是停止倒计时，还是修改button的title
        if (copy_self.timeout <= 0) {
            copy_self.timeout = 120;
            [copy_self uploadLocation];
        }
    });
    dispatch_resume(copy_self.timer);
    
    
    return YES;
}

//iOS10以下使用这两个方法接收通知
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    SJLog(@"7.0-didrexeive---%@",userInfo);
    [UMessage setBadgeClear:YES];
    [UMessage setAutoAlert:NO];
    if([[[UIDevice currentDevice] systemVersion]intValue] < 10){
        [UMessage didReceiveRemoteNotification:userInfo];
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    SJLog(@"10.0-前台-didrexeive---%@",userInfo);
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [UMessage setAutoAlert:NO];
        //应用处于前台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
    }else{
        //应用处于前台时的本地推送接受
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    SJLog(@"10.0-点击-didrexeive---%@",userInfo);
    
    [UMessage setBadgeClear:YES];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
    }else{
        //应用处于后台时的本地推送接受
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);

}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    SJLog(@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                  stringByReplacingOccurrencesOfString: @">" withString: @""]
                 stringByReplacingOccurrencesOfString: @" " withString: @""]);
    
    NSString *devTok = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                         stringByReplacingOccurrencesOfString: @">" withString: @""]
                        stringByReplacingOccurrencesOfString: @" " withString: @""];
    [[NSUserDefaults standardUserDefaults]setObject:devTok forKey:DeviceToken];
    if ([UserInfoTool shareUserInfoTool].Info.Role) {
        if ([[UserInfoTool shareUserInfoTool].Info.Role  isEqualToString:@"030003002"]) {
            //绑定别名
            NSString *alias = [NSString stringWithFormat:@"%d",[UserInfoTool shareUserInfoTool].Info.ID];
            [UMessage addAlias:alias type:@"WORKER_TYPE" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
                SJLog(@"%@-%@",responseObject,error);
            }];
        }
    }
    
}

-(void)uploadLocation{
    double latitude = [[NSUserDefaults standardUserDefaults] doubleForKey:latitudeStr];
    double longtatude = [[NSUserDefaults standardUserDefaults] doubleForKey:longtatudeStr];
    if (latitude == 0  || longtatude == 0) {
        SJLog(@"无法获取位置信息");
        return;
    }
    
    if (![UserInfoTool shareUserInfoTool].Info.WxID) {
        SJLog(@"没有微信ID");
        return;
    }
    if (![UserInfoTool shareUserInfoTool].Info.ID) {
        SJLog(@"没有用户ID");
        return;
    }
    NSDictionary *params = @{@"openid":[UserInfoTool shareUserInfoTool].Info.WxID,@"uid":[UserInfoTool shareUserInfoTool].Info.WxID,@"lat":@(latitude),@"lng":@(longtatude)};
    [[SJNetWorkTool sharedTool] requestWithURLString:uploadLocation parameters:params method:POST callBack:^(id responseObject, NSError *error) {
        if (error) {
            [self uploadLocation];
        }else{
            int a = [responseObject[@"Code"] intValue];
            if (a != 1) {
                [self uploadLocation];
            }
        }
    }];
    
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    SJLog(@"定位失败");
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *location = locations.lastObject;
//    SJLog(@"---%lf----%lf",location.coordinate.latitude,location.coordinate.longitude);
    
    [[NSUserDefaults standardUserDefaults] setDouble:location.coordinate.latitude forKey:latitudeStr];
    [[NSUserDefaults standardUserDefaults] setDouble:location.coordinate.longitude forKey:longtatudeStr];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
//    [self.locationManager stopUpdatingLocation];
}
//这个方法 每次启动都会走
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    SJLog(@"%@",[NSThread currentThread]);
    if ((status == kCLAuthorizationStatusAuthorizedWhenInUse) | kCLAuthorizationStatusAuthorizedAlways) {
        [self.locationManager startUpdatingLocation];
    }else{
        SJLog(@"获取位置信息失败");
    }
}




-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    
    return [WXApi handleOpenURL:url delegate:self];
}
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return [WXApi handleOpenURL:url delegate:self];
}
#pragma mark 微信回调的代理方法
- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp *response = (PayResp *)resp;
        NSString *message;
        switch (response.errCode) {
            case WXSuccess:
            {
                message=@"支付成功";
                [[NSNotificationCenter defaultCenter] postNotificationName:wxPaySuccessNotification object:nil];
            }
                break;
            case WXErrCodeCommon:
                //普通错误类型
                message=@"支付错误";
                [[NSNotificationCenter defaultCenter] postNotificationName:wxPayFaileNotification object:message];
                break;
            case WXErrCodeUserCancel:
                //用户点击取消并且返回
                message=@"您取消了交易";
                [[NSNotificationCenter defaultCenter] postNotificationName:wxPayFaileNotification object:message];
                break;
            case WXErrCodeSentFail:
                //发送失败
                message=@"信息发送失败";
                [[NSNotificationCenter defaultCenter] postNotificationName:wxPayFaileNotification object:message];
                break;
            case WXErrCodeAuthDeny:
                //授权失败
                message=@"授权失败";
                [[NSNotificationCenter defaultCenter] postNotificationName:wxPayFaileNotification object:message];
                break;
            case WXErrCodeUnsupport:
                //微信不不支持
                message=@"您的微信版本过低";
                [[NSNotificationCenter defaultCenter] postNotificationName:wxPayFaileNotification object:message];
                break;
            default:
                NSLog(@"failed");
                break;
        }
    }
}

-(void)applicationWillEnterForeground:(UIApplication *)application{
   [SJRootChoose synclogin];
}



@end
